package com.etc.doctor.service.impl;

import cn.hutool.json.JSONUtil;
import com.etc.doctor.entity.Department;
import com.etc.doctor.mapper.DepartmentMapper;
import com.etc.doctor.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.etc.common.utils.RedisConstants.CACHE_DEPARTMENT;


@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<Department> queryAll() {
        Boolean isExist = stringRedisTemplate.hasKey(CACHE_DEPARTMENT);
        //判断redis中是否有缓存
        if (isExist) {
            //有缓存,获取缓存
            List<String> json = stringRedisTemplate.opsForList().range(CACHE_DEPARTMENT, 0, -1);
            //转化成list
            List<Department> list = JSONUtil.toList(json.toString(), Department.class);
            return list;
        }
        List<Department> list = departmentMapper.queryAll();
        //新增到redis
        for (Department department : list) {
            //转化成json
            String jsonStr = JSONUtil.toJsonStr(department);
            //写入redis
            stringRedisTemplate.opsForList().leftPush(CACHE_DEPARTMENT, jsonStr);
        }
        return list;
    }
}
